package com.ruoyi.system.coretools.apple;

import cn.hutool.http.HttpUtil;
import com.auth0.jwk.Jwk;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AppPublicKey {
    private static final Logger log = LoggerFactory.getLogger(AppPublicKey.class);
    public static volatile Map<String, Map<String, Object>> cache = new HashMap<>();

    public static PublicKey get(String url, String kid) {
        try {
            if (cache.containsKey(kid)) {
                Map<String, Object> publicKeyConfig = cache.get(kid);
                Jwk jwa = Jwk.fromValues(publicKeyConfig);
                return jwa.getPublicKey();
            }
            Map<String, Object> publicKeyConfig = getPublicKeyConfig(url, kid);
            if (null == publicKeyConfig) {
                return null;
            }
            Jwk jwa = Jwk.fromValues(publicKeyConfig);
            return jwa.getPublicKey();
        } catch (final Exception e) {
            log.error("apple get publicKey error", e);
        }

        return null;
    }

    private static synchronized Map<String, Object> getPublicKeyConfig(String url, String kid) {
        try {
            String str = HttpUtil.get(url);
            JsonNode jsonNode = JsonHelper.asTree(str);
            JsonNode keys = jsonNode.get("keys");
            if (null == keys) {
                return null;
            }
            Iterator<JsonNode> elements = keys.elements();

            while (elements.hasNext()) {
                JsonNode node = elements.next();
                String nodeKid = node.get("kid").asText();
                if (kid.equals(nodeKid)) {
                    Map<String, Object> item = JsonHelper.toMap(node);
                    cache.put(nodeKid, item);
                }
            }
            return cache.get(kid);
        } catch (final Exception e) {
            log.error("apple get publicKey error", e);
        }
        return null;
    }
}
